<template>
  <MySplitPanes>
    <pane>
      <div class="my-flex-column w100 h100">
        <el-card v-show="state.showQuery" class="my-query-box mt8" shadow="never" :body-style="{ paddingBottom: '0' }">
          <el-form :inline="true" label-width="auto" @submit.stop.prevent>
            <el-form-item>
              <my-select-input v-model="state.pageInput.dynamicFilter" :filters="state.filters" @search="onQuery" />
            </el-form-item>
            <el-form-item :label="$t('message.label1.l1')">
              <el-select v-model="state.pageInput.filter.stationId" :placeholder="$t('message.label1.l2')" clearable
                style="width: 150px">
                <el-option v-for="item in state.stationTreeData" :key="item.id" :label="item.stationCode"
                  :value="item.id">
                  <span style="float: left">{{ item.stationCode }}</span>
                  <span style="
                              float: right;
                              color: var(--el-text-color-secondary);
                              font-size: 13px;">
                    {{ item.stationName }}
                  </span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <MyDateTimeRange v-model:startDate="state.pageInput.filter.startTime"
                v-model:endDate="state.pageInput.filter.endTime" style="width: 230px" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="ele-Search" @click="onQuery"> {{ $t('message.label1.l3') }} </el-button>
              <el-button type="primary" icon="ele-Search" @click="onFilter"> {{ $t('message.label1.l4') }} </el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <el-card class="my-fill mt8" shadow="never">
          <div class="my-tools-box mb8 my-flex my-flex-between">
            <div>
              <el-button v-auth="'api:industry:work-station-record:export-data'" icon="ele-Upload" type="primary"
                :loading="state.export.loading" @click="onExport">
                {{ $t('message.label1.l5') }}
              </el-button>
              <el-button v-auth="'api:industry:work-station-record:export-process-data'" icon="ele-Upload"
                type="primary" :loading="state.export.loading" @click="onExportProcess">
                {{ $t('message.label1.l6') }}
              </el-button>
            </div>
            <div v-if="state.progressStatus" style="width: 500px;">
              <el-progress :text-inside="true" :stroke-width="26" status="success" striped striped-flow :duration="10"
                :percentage=state.progress />
            </div>
            <div>
              <el-tooltip effect="dark" :content="state.showQuery ? '隐藏查询' : '显示查询'" placement="top">
                <el-button :icon="state.showQuery ? 'ele-ArrowUp' : 'ele-ArrowDown'" circle
                  @click="state.showQuery = !state.showQuery" />
              </el-tooltip>
            </div>
          </div>

          <el-table ref="tableRef" v-loading="state.loading" :data="state.workStationRecordListData" row-key="id">
            <!-- <el-table-column type="selection" /> -->
            <el-table-column prop="productCode" :label="$t('message.label1.l9')" width="250" show-overflow-tooltip
              fixed="left" />
            <el-table-column prop="stationCode" :label="$t('message.label1.l10')" width="100" show-overflow-tooltip />
            <el-table-column prop="stationName" :label="$t('message.label1.l11')" width="100" show-overflow-tooltip />
            <el-table-column prop="productModelCode" :label="$t('message.label1.l12')" width="120"
              show-overflow-tooltip />
            <el-table-column prop="productModelName" :label="$t('message.label1.l13')" width="120"
              show-overflow-tooltip />
            <el-table-column prop="startTime" :label="$t('message.label1.l14')" width="200" show-overflow-tooltip />
            <el-table-column prop="endTime" :label="$t('message.label1.l15')" width="200" show-overflow-tooltip />
            <el-table-column prop="cycleTime" :label="$t('message.label1.l16')" width="100" show-overflow-tooltip />
            <el-table-column prop="result" :label="$t('message.label1.l17')" width="80" show-overflow-tooltip
              align="center" fixed="right">
              <template #default="{ row }">
                <el-tag v-if="row.result == 'OK'" type="success">{{ row.result }}</el-tag>
                <el-tag v-else type="danger">{{ row.result }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="slot" :label="$t('message.label1.l19')" width="120" show-overflow-tooltip />
            <el-table-column prop="createdTime" :label="$t('message.label1.l18')" width="200" show-overflow-tooltip />
          </el-table>
          <div class="my-flex my-flex-end" style="margin-top: 10px">
            <el-pagination v-model:currentPage="state.pageInput.currentPage"
              v-model:page-size="state.pageInput.pageSize" :total="state.total" :page-sizes="[10, 20, 50, 100]" small
              background @size-change="onSizeChange" @current-change="onCurrentChange"
              layout="total, sizes, prev, pager, next, jumper" />
          </div>
        </el-card>
        <MyFilterDialog ref="myFilterDialogRef" :fields="state.filters" @sure="onFilterSure"></MyFilterDialog>
      </div>
    </pane>
  </MySplitPanes>
</template>
<script setup lang="ts" name="work-station-record">
import { ref, reactive, onMounted, getCurrentInstance, onBeforeMount, defineAsyncComponent } from 'vue'
import { PageInputWorkStationRecordGetPageInput, WorkStationRecordGetPageOutput, WorkStationGetListOutput } from '/@/api/industry/data-contracts'
import { Pane } from 'splitpanes'
import eventBus from '/@/utils/mitt'
import { auth } from '/@/utils/authFunction'
import { ElTable } from 'element-plus'
import { WorkStationRecordApi } from '/@/api/industry/WorkStationRecord'
import { WorkStationApi } from '/@/api/industry/WorkStation'
import { RequestParams } from '/@/api/admin/http-client'
import dayjs from 'dayjs'
import { useI18n } from 'vue-i18n'
import { listToTree } from '/@/utils/tree'
const MySplitPanes = defineAsyncComponent(() => import('/@/components/my-layout/split-panes.vue'))
const MySelectInput = defineAsyncComponent(() => import('/@/components/my-select-input/index.vue'))
const MyFilterDialog = defineAsyncComponent(() => import('/@/components/my-filter/dialog.vue'))
const MyDateTimeRange = defineAsyncComponent(() => import('/@/components/my-datetime-range/index.vue'))
const { t } = useI18n();
const { proxy } = getCurrentInstance() as any
const myFilterDialogRef = ref();
const state = reactive({
  progressStatus: false,
  loading: false,
  showQuery: true,
  total: 0,
  progress: 0,
  export: {
    loading: false,
  },
  pageInput: {
    currentPage: 1,
    pageSize: 20,
    filter: {
      stationId: null,
      startTime: null,
      endTime: null
    },
    dynamicFilter: {},
  } as PageInputWorkStationRecordGetPageInput,
  stationTreeData: [] as WorkStationGetListOutput[],
  workStationRecordListData: [] as Array<WorkStationRecordGetPageOutput>,
  filters: [
    {
      field: 'productCode',
      operator: 'Contains',
      description: t('message.label1.l9'),
      componentName: 'el-input',
      defaultSelect: true,
    },
    {
      field: 'result',
      operator: 'Contains',
      description: t('message.label1.l17'),
      componentName: 'el-input',
      defaultSelect: false,
    },
    {
      field: 'slot',
      operator: 'Contains',
      description: t('message.label1.l19'),
      componentName: 'el-input',
      defaultSelect: false,
    }
  ] as Array<DynamicFilterInfo>,
})
onMounted(async () => {
  getStations()
  getProgess(false)
  await onQuery();
  eventBus.off('refreshWorkStationRecord')
  eventBus.on('refreshWorkStationRecord', async () => {
    onQuery()
  })
})
onBeforeMount(() => {
  eventBus.off('refreshWorkStationRecord')
})
const getStations = async () => {
  const res = await new WorkStationApi().getList({})
  if (res?.success && res.data && res.data.length > 0) {
    state.stationTreeData = listToTree(res.data) as WorkStationGetListOutput[]
  } else {
    state.stationTreeData = []
  }
}
const getProgess = (cache: boolean) => {
  const timer = setInterval(async () => {
    const statusRes = await new WorkStationRecordApi().exportProgress();
    if (statusRes.data == 0 && !cache) {
      clearInterval(timer);
    }
    state.progress = Math.floor(statusRes.data);
    let file = '';
    if (statusRes.data > 0 || cache) {
      state.progressStatus = true;
      state.export.loading = true
      const resFileName = await new WorkStationRecordApi().exportFileName().catch(() => {
      });
      if (resFileName?.success) {
        file = resFileName.data
      }
    }
    if (statusRes.data == 100) {
      clearInterval(timer);
      state.progressStatus = false
      state.export.loading = false
      await new WorkStationRecordApi().exprotFile({ fileName: file }, { format: 'blob', returnResponse: true })
        .then((res: any) => {
          const contentDisposition = res.headers['content-disposition']
          const matchs = /filename="?([^;"]+)/i.exec(contentDisposition)
          let fileName = ''
          if (matchs && matchs.length > 1) {
            fileName = decodeURIComponent(matchs[1])
          } else {
            fileName = file
          }
          const a = document.createElement('a')
          a.download = fileName
          a.href = URL.createObjectURL(res.data as Blob)
          a.click()
          URL.revokeObjectURL(a.href)
        });

    }
  }, 4000);
}
//查询分页
const onQuery = async () => {
  state.loading = true
  const res = await new WorkStationRecordApi().getPage(state.pageInput).catch(() => {
    state.loading = false
  })

  state.workStationRecordListData = res?.data?.list ?? []
  state.total = res?.data?.total ?? 0
  state.loading = false
}
//高级查询
const onFilter = () => {
  myFilterDialogRef.value.open()
}

const onFilterSure = (dynamicFilter: any) => {
  state.pageInput.dynamicFilter = dynamicFilter
  onQuery()
}
//导出
const onExport = async () => {
  state.export.loading = true

  await new WorkStationRecordApi()
    .exportData(
      {
        dynamicFilter: state.pageInput.dynamicFilter,
        sortList: state.pageInput.sortList,
      },
      { format: 'blob', returnResponse: true }
    )
    .then((res: any) => {
      const contentDisposition = res.headers['content-disposition']
      const matchs = /filename="?([^;"]+)/i.exec(contentDisposition)
      let fileName = ''
      if (matchs && matchs.length > 1) {
        fileName = decodeURIComponent(matchs[1])
      } else {
        fileName = `产品加工参数记录列表${dayjs().format('YYYYMMDDHHmmss')}.xlsx`
      }
      const a = document.createElement('a')
      a.download = fileName
      a.href = URL.createObjectURL(res.data as Blob)
      a.click()
      URL.revokeObjectURL(a.href)
    })
    .finally(() => {
      state.export.loading = false
    })
}

//导出
const onExportProcess = async () => {
  state.export.loading = true
  state.progress = 0;
  let currenFile = `ProcessData${dayjs().format('YYYYMMDDHHmmss')}.xlsx`;
  const res = await new WorkStationRecordApi()
    .exportProcessData(
      {
        dynamicFilter: state.pageInput.dynamicFilter,
        sortList: state.pageInput.sortList,
        filter: state.pageInput.filter
      }
    ).catch(() => {
      state.export.loading = false
    });
  if (res?.success) {
    getProgess(true)
  }
}
const onSizeChange = (val: number) => {
  state.pageInput.currentPage = 1
  state.pageInput.pageSize = val
  onQuery()
}

const onCurrentChange = (val: number) => {
  state.pageInput.currentPage = val
  onQuery()
}
</script>